package com.dhj.jvmstudy.chapter08;

import java.util.ArrayList;
import java.util.List;

public class StopTheWorldDemo {

    public static class WorkThread extends Thread {
        List<byte[]> list = new ArrayList<byte[]>();

        public void run(){
            try {
                while (true){
                    for (int i=0; i<1000; i++){
                        byte[] buffer = new byte[1024];
                        list.add(buffer);
                    }

                    if(list.size() > 10000){
                        list.clear();
                        System.gc();  // 会触发full gc操作，进而会出现STW事件。
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static class PrintTread extends Thread {
        public final long startTime = System.currentTimeMillis();

        @Override
        public void run() {
            try {
                while (true){
                    // 每秒打印时间信息
                    long t = System.currentTimeMillis() - startTime;
                    System.out.println(t / 1000 +"."+t % 1000);
                    Thread.sleep(1000);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WorkThread w = new WorkThread();
        PrintTread p = new PrintTread();
        w.start();
        p.start();
    }

}
